package com.zzjson.io.nio.buffer;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>****************************************************************************</p>
 * <p><b>Copyright © 2010-2019 shuncom team All Rights Reserved<b></p>
 * <ul style="margin:15px;">
 * <li>Description : cn.zzjson.io.nio.buffer</li>
 * <li>Version     : 1.0.0</li>
 * <li>Creation    : 2019年03月26日</li>
 * <li>@author     : zzy0_0</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class BufferProgram {
    public static void main(String[] args) {
        FileInputStream fileInputStream = null;
        FileChannel fileChannel = null;
        try {
            //使用文件io流
            fileInputStream = new FileInputStream("/Users/zzy/git/learning/src/cn/zzjson/io/nio/buffer/test.txt");
            //创建文件的操作管道
            fileChannel = fileInputStream.getChannel();

            ByteBuffer buffer = ByteBuffer.allocate(10);
            output("初始化", buffer);

            while (fileChannel.read(buffer) > 0) {

                output("调用read", buffer);

                buffer.flip();
                output("调用filp", buffer);

                List<Byte> byteList = new ArrayList<>();
                while (buffer.hasRemaining()) {
                    byte b = buffer.get();
                    byteList.add(b);
                    output("调用get", buffer);
                }
                print(byteList);

                buffer.clear();
                output("调用clear", buffer);
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (fileChannel != null) {
                    fileChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private static void print(List<Byte> byteList) {
        System.out.println("读取到的内容为");
        for (Byte aByte : byteList) {
            System.out.print((char) aByte.byteValue());
        }
        System.out.println();
        System.out.println();
    }

    //把这个缓冲里面实时状态给答应出来
    public static void output(String step, Buffer buffer) {
        System.out.println(step + " : ");
        //容量，数组大小
        System.out.print("capacity: " + buffer.capacity() + ", ");
        //当前操作数据所在的位置，也可以叫做游标
        System.out.print("position: " + buffer.position() + ", ");
        //锁定值，flip，数据操作范围索引只能在position - limit 之间
        System.out.println("limit: " + buffer.limit());
        System.out.println();
    }
}